<template>
    <div>
      <div>
        <span>
          当前数据源：
          <Tag color="green">{{ data.dsName }}</Tag>
        </span>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <span>
          当前数据库：
          <Select
            v-model:value="data.databaseName"
            style="width: 200px"
            placeholder="选择数据库"
            :options="databases"
            :field-names="{ label: 'name', value: 'name' }"
            size="small"
            @change="onDatabaseChange"
          />
        </span>
      </div>
      <div style="width: 100%; height: 8px"></div>
      <MonacoEditor
        width="100%"
        :height="300"
        v-model:database="data.databaseName"
        :onEditAction="onQueryAction"
        @onQuery="handleQuery"
      />
      <div>
        {{ queryResult }}
        <Table
          size="small"
          :columns="queryResultColumns"
          @resizeColumn="handleResizeColumn"
          :data-source="queryResultData"
          :pagination="false"
          bordered
          :scroll="{ x: 1200, y: 390 }"
        />
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { ref, defineProps, onMounted } from 'vue'
  import { Tag, Select, Table } from 'ant-design-vue'
  import MonacoEditor from './MonacoEditor.vue'

interface QueryPanelProps {
  data: {
    dsId: number
    dsName: string
    databaseName: string
  }
  databases: Array<{ name: string }>
  onQueryAction: (action: any, data: any) => any
}

const props = defineProps<QueryPanelProps>()

// 使用 reactive 创建 data 对象并绑定 props 的值
const data = ref<{
    dsId: number
    dsName: string
    databaseName: string
  }>({
    dsId: props.data.dsId,
    dsName: props.data.dsName,
    databaseName: "mysql",
  })
  
  // 定义响应式数据
  const queryResultColumns = ref<any[]>([])
  const queryResultData = ref<any[]>([])
  const queryResult = ref("")
  
  // 数据库选择变化处理
//   const handleDatabaseChange = (newDatabase: string) => {
//     console.log('Database changed to:', newDatabase)
//     props.data.databaseName = newDatabase
//   }
  
  // 查询操作
  const handleQuery = async (query: {database: string; sql: string}) => {
    console.log('Executing query:', query)
    let headers = new Array();
    try {
    const res = await props.onQueryAction("query", {
        dsId: props.data.dsId,
        database: query.database,
        sql: query.sql
    })
    console.log(res)

    queryResult.value = "记录条数: " + res.affectedRows;

    if (res.headers) {
      for (let i = 0; i < res.headers.length; i++) {
        headers.push({
          title: res.headers[i],
          dataIndex: res.headers[i],
          ellipsis: true,
          resizable: true,
          minWidth: 50,
          customRender: function (text, r, index) {
            return text.text || "NULL";
          },
        });
      }
    }
    queryResultColumns.value = headers;
    queryResultData.value = res.result;
  } catch (error: any) {
    queryResult.value = error.message;
    queryResultColumns.value = headers;
    queryResultData.value = [];
  }
  }
  
  // 表格列宽调整
  const handleResizeColumn = (column: any) => {
    console.log('Resizing column:', column)
  }

  const onDatabaseChange = async (value) => {
    console.log('onDatabaseChange:', value)
    data.value.databaseName = value
  }

onMounted(() => {
    data.value = {
        dsId: props.data.dsId,
        dsName: props.data.dsName,
        databaseName: props.data.databaseName,
    }
})
  </script>
  
  <style scoped>
  /* 子组件样式 */
  </style>